// $Id: result.cpp 2 2009-09-02 08:47:42Z joseph2002 $
/*
 * Copyright 2008-2009 Joseph Wu
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
 *
 * For more information, see http://xpcomplus.sourceforge.net
 */

#define XPCOM_SOURCE

#include <xpcom/config.hpp>
#include <algorithm>
#include <xpcom/result.hpp>
#include <xpcom/string.hpp>
#include <xpcom/detail/hex_format.hpp>

namespace xpcom {

namespace {

// Length of string for conversion
const uint32_t string_len = 10;

// Format of result is 0x{8 hex digits}
template <typename CharT>
inline CharT* write_str(result_t val, CharT* s, uint32_t size)
{
    if (!s || size < string_len)
        return 0;

    *s++ = CharT('0');
    *s++ = CharT('x');

    return detail::hex_write_upper(s, val);
}

} // anonymous namespace

result::result(uint16_t severity, uint16_t module, uint16_t code) throw() :
    val_(XPCOM_MAKE_RESULT(severity, module, code))
{
}

uint16_t result::severity() const throw()
{
    return XPCOM_RESULT_SEVERITY(val_);
}

uint16_t result::module() const throw()
{
    return XPCOM_RESULT_MODULE(val_);
}

uint16_t result::code() const throw()
{
    return XPCOM_RESULT_CODE(val_);
}

void result::swap(result& rhs) throw()
{
    std::swap(val_, rhs.val_);
}

template <typename CharT>
void result::to_str(basic_string<CharT>& str) const
{
    typedef basic_string<CharT> string_type;
    str.resize(string_len);
    write_str(val_, &str[0], str.size());
}

template XPCOM_DECL void result::to_str(basic_string<char>&) const;
template XPCOM_DECL void result::to_str(basic_string<wchar>&) const;

string result::str() const
{
    string s;
    to_str(s);
    return s;
}

wstring result::wstr() const
{
    wstring s;
    to_str(s);
    return s;
}

} // namespace xpcom
